#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;
using Premiere.DTO;
using Premiere.Window;
using System.Collections;
using Premiere.Framework;

#endregion

namespace PremiereMX
{
    public partial class UserControlOpeningStock : UserControl, IUserControlOpeningStock
    {
        OpeningStockLogic m_logic;
        IMainForm m_mainForm;
        Hashtable m_items = new Hashtable();
        bool b_init, m_readOnly = false;
        bool m_isAutoNumber = false;

        public UserControlOpeningStock(string name, IMainForm mainForm)
        {
            InitializeComponent();
            m_logic = new OpeningStockLogic(mainForm, this);
            m_mainForm = mainForm;
            this.Name = name;
            this.Dock = DockStyle.Fill;
            InitButtonClick();
            InitGridValidation();
           // dataGridView1.RowCount = 500;
        }

        private void InitGridValidation()
        {
            dataGridView1.CellValidating += new DataGridViewCellValidatingEventHandler(dataGridView1_CellValidating);
            dataGridView1.CellValidated += new DataGridViewCellEventHandler(dataGridView1_CellValidated);
            dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(dataGridView1_CellValueChanged);
        }

        void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (m_readOnly) return;
            updateDecimalCurrency(e.RowIndex);
        }

        void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            if (m_readOnly) return;
            if (itemDTO(e.RowIndex) == null) return;
            if (itemDTO(e.RowIndex).Part == null) return;
            dataGridView1.CurrentRow.ErrorText = "";
            if (e.ColumnIndex == dataGridViewTextBoxColumnCode.Index)
            {
                dataGridView1[dataGridViewTextBoxColumnName.Index, e.RowIndex].Value = null;
                dataGridView1[dataGridViewComboBoxColumnUOM.Index, e.RowIndex].Value = null;
                dataGridView1[dataGridViewTextBoxColumnQTY.Index, e.RowIndex].Value = "0";
                dataGridView1[dataGridViewTextBoxColumnPrice.Index, e.RowIndex].Value = "0";
                ((DataGridViewComboBoxCell)dataGridView1[dataGridViewComboBoxColumnUOM.Index, e.RowIndex]).DataSource = null;

                PartDTO part = itemDTO(e.RowIndex).Part;
                part = (PartDTO)ServiceRegistry.GetInstance().GetPartService().Get(part.Id);
                itemDTO(e.RowIndex).Part = part;

                ((DataGridViewComboBoxCell)dataGridView1[dataGridViewComboBoxColumnUOM.Index, e.RowIndex]).DataSource = Utils.GetListToString(part.GetAllUoM());
                dataGridView1[dataGridViewTextBoxColumnCode.Index, e.RowIndex].Value = part.Code;
                dataGridView1[dataGridViewTextBoxColumnName.Index, e.RowIndex].Value = part.Name;
                dataGridView1[dataGridViewComboBoxColumnUOM.Index, e.RowIndex].Value = part.Unit.ToString();
                dataGridView1[dataGridViewTextBoxColumnQTY.Index, e.RowIndex].Value = "1";
                dataGridView1[dataGridViewTextBoxColumnPrice.Index, e.RowIndex].Value = part.CostPrice;

                itemDTO(e.RowIndex).Unit = part.Unit;
                itemDTO(e.RowIndex).Amount = 1m;
                itemDTO(e.RowIndex).Price = part.CostPrice;
                itemDTO(e.RowIndex).Warehouse = (WarehouseDTO)warehouseComboBox.SelectedItem;
                updateDecimalCurrency(e.RowIndex);
                updateSubTotal(e.RowIndex);
                
            }
            

            if (e.ColumnIndex == dataGridViewComboBoxColumnUOM.Index)
            {

               

                UnitDTO unit = (UnitDTO)Utils.FindDTOInList(dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString(),
                    itemDTO(e.RowIndex).Part.GetAllUoM());
                itemDTO(e.RowIndex).Unit = unit;
                decimal price = 0m;
                if (itemDTO(e.RowIndex).Part.Unit.Id == unit.Id)
                    price = itemDTO(e.RowIndex).Part.CostPrice;
                else
                    price = itemDTO(e.RowIndex).Part.GetUnitConversion(unit.Id).CostPrice;
                
                dataGridView1[dataGridViewTextBoxColumnPrice.Index, e.RowIndex].Value = price;
                itemDTO(e.RowIndex).Price = price;

                updateDecimalCurrency(e.RowIndex);
                updateSubTotal(e.RowIndex);
                
            }

            if (e.ColumnIndex == dataGridViewTextBoxColumnPrice.Index
                || e.ColumnIndex == dataGridViewTextBoxColumnQTY.Index)
            {
                decimal qty = Convert.ToDecimal(dataGridView1[dataGridViewTextBoxColumnQTY.Index, e.RowIndex].Value);
                qty = Math.Round(qty, 0);
                decimal price = Convert.ToDecimal(dataGridView1[dataGridViewTextBoxColumnPrice.Index, e.RowIndex].Value);
                price = Math.Round(price, TransactionCurrency.DecimalPlace);

                itemDTO(e.RowIndex).Amount = qty;
                itemDTO(e.RowIndex).Price = price;

                dataGridView1[dataGridViewTextBoxColumnQTY.Index, e.RowIndex].Value = qty.ToString();
                dataGridView1[dataGridViewTextBoxColumnPrice.Index, e.RowIndex].Value = price.ToString(Tools.CreateFormat(TransactionCurrency.DecimalPlace));

                updateDecimalCurrency(e.RowIndex);
                updateSubTotal(e.RowIndex);
                
            }
        }

        private void updateDecimalCurrency(int r)
        {
            dataGridView1[dataGridViewTextBoxColumnPrice.Index, r].Style.Format = "N" + TransactionCurrency.DecimalPlace;
            dataGridView1[dataGridViewTextBoxColumnSubTotal.Index, r].Style.Format = "N" + TransactionCurrency.DecimalPlace;
        }
        void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (m_readOnly) return;
            if (TransactionCurrency == null)
            {
                dataGridView1.CurrentRow.ErrorText = "Currency is not set";
                e.Cancel = true;
                return;
            }
            if (warehouseComboBox.SelectedItem == null)
            {
                dataGridView1.CurrentRow.ErrorText = "Warehouse is not set";
                e.Cancel = true;
                return;
            }
            if (e.ColumnIndex == dataGridViewTextBoxColumnCode.Index)
            {
                PartDTO part = null;
                OpeningStockItemDTO opitem = (OpeningStockItemDTO)dataGridView1.Rows[e.RowIndex].Tag;
                if (opitem == null)
                {
                    opitem = new OpeningStockItemDTO();
                    dataGridView1.Rows[e.RowIndex].Tag = opitem;
                }
                FieldInfo f = (FieldInfo)m_logic.FieldList[0];
                f.Value = e.FormattedValue.ToString();
                IList result = ServiceRegistry.GetInstance().GetPartService().FindByField(f);
                if (result.Count > 0)
                {
                    part = (PartDTO)result[0];
                    opitem.Part = part;
                    return;
                }
                else
                {
                    dataGridView1.CurrentRow.ErrorText = "part not found";
                    e.Cancel = true;
                    return;
                }
            }
            if (itemDTO(e.RowIndex) == null)
            {
                dataGridView1.CurrentRow.ErrorText = "Please select part not found";
                e.Cancel = true;
                return;
            }
            if (e.ColumnIndex == dataGridViewTextBoxColumnPrice.Index || 
                e.ColumnIndex == dataGridViewTextBoxColumnQTY.Index)
            {
                try
                {
                    Convert.ToDecimal(e.FormattedValue);
                }
                catch (Exception x)
                {
                    dataGridView1.CurrentRow.ErrorText = x.Message;
                    e.Cancel = true;
                    return;
                }
            }
        }
        private OpeningStockItemDTO itemDTO(int row)
        {
            return (OpeningStockItemDTO)dataGridView1.Rows[row].Tag;
        }
        private void updateSubTotal(int row)
        {
            decimal a = itemDTO(row).Amount;
            decimal b = itemDTO(row).Price;
            decimal x = Tools.Calculate(a, b, TransactionCurrency.DecimalPlace);
            itemDTO(row).TotalAmount = x;
            dataGridView1[dataGridViewTextBoxColumnSubTotal.Index, row].Value = x.ToString(Tools.CreateFormat(TransactionCurrency.DecimalPlace));  
            ReCalculateNetTotal();
        }
        private void ReCalculateNetTotal()
        {
            IList totalAmount = new ArrayList();
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                OpeningStockItemDTO dto = itemDTO(i);
                if (dto == null) continue;
                if (dto.Part == null) continue;
                totalAmount.Add(dto.TotalAmount);
            }
            TotalAllAmount = Tools.CalculateSumList(totalAmount, TransactionCurrency == null ? 2 : TransactionCurrency.AutoAdjustment);
        }
        private void InitButtonClick()
        {
            toolBarButtonSave.Click += new EventHandler(toolBarButtonSave_Click);
            toolBarButtonDelete.Click += new EventHandler(toolBarButtonDelete_Click);
            toolBarButtonEdit.Click += new EventHandler(toolBarButtonEdit_Click);
            toolBarButtonNew.Click += new EventHandler(toolBarButtonNew_Click);
            toolBarButtonPrint.Click += new EventHandler(toolBarButtonPrint_Click);
            toolBarButtonRefresh.Click += new EventHandler(toolBarButtonRefresh_Click);
            buttonSave.Click += new EventHandler(toolBarButtonSave_Click);
            buttonDelete.Click += new EventHandler(toolBarButtonDelete_Click);
            buttonEdit.Click += new EventHandler(toolBarButtonEdit_Click);
            buttonNew.Click += new EventHandler(toolBarButtonNew_Click);
        }
        void toolBarButtonRefresh_Click(object sender, EventArgs e)
        {
            Refresh();
        }

        void toolBarButtonPrint_Click(object sender, EventArgs e)
        {
            m_logic.Print();
        }

        void toolBarButtonNew_Click(object sender, EventArgs e)
        {
            m_logic.New();
        }

        void toolBarButtonEdit_Click(object sender, EventArgs e)
        {
            m_logic.Edit();
        }

        void toolBarButtonDelete_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Are you sure to delete this record?", "Confirmation", MessageBoxButtons.YesNo,
                 MessageBoxIcon.Question, new EventHandler(DeleteConfirmation));
        }
        void DeleteConfirmation(object sender, EventArgs e)
        {
            MessageBoxWindow msg = (MessageBoxWindow)sender;
            if (msg.DialogResult == DialogResult.Yes)
                m_logic.Delete();
        }

        void toolBarButtonSave_Click(object sender, EventArgs e)
        {
            m_logic.Save();
        }
        private void listViewRecords_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listViewRecords.SelectedItem == null) return;
            OpeningStockDTO user = (OpeningStockDTO)listViewRecords.SelectedItem.Tag;
            m_logic.UpdateSubject(user);
        }


        #region IUserControlDivision Members

        public string Code
        {
            get
            {
                return textBoxCode.Text;
            }
            set
            {
                textBoxCode.Text = value;
            }
        }
        public DateTime LastUpdate
        {
            set { statusBar1.Text = statusBar1.Text + " - Last Updated on : " + value.ToString("dd-MMM-yyyy"); }
        }

        public string ComputerName
        {
            set { statusBar1.Text = statusBar1.Text + " - Computer Name : " + value; }
        }

        public string UserUpdateBy
        {
            set { statusBar1.Text = statusBar1.Text + " - Last Updated By : " + value; }
        }

        public void ShowMessage(string mess)
        {
            MessageBox.Show(mess, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        public void UpdateList(System.Collections.IList list)
        {
            foreach (OpeningStockDTO curr in list)
            {
                if (m_items.ContainsKey(curr.Id))
                {
                    ListViewItem item = (ListViewItem)m_items[curr.Id];
                    item.SubItems[0].Text = curr.Code;
                    item.SubItems[1].Text = curr.Code;
                    item.SubItems[2].Text = curr.Code;
                    item.SubItems[3].Text = curr.LastUpdate.ToString("dd-MMM-yyyy hh:mm:ss");
                    item.SubItems[4].Text = curr.UserName;
                }
                else
                {
                    ListViewItem item = listViewRecords.Items.Add(curr.Code);
                    item.SubItems.Add(curr.Code);
                    item.SubItems.Add(curr.Code);
                    item.SubItems.Add(curr.LastUpdate.ToString("dd-MMM-yyyy hh:mm:ss"));
                    item.SubItems.Add(curr.UserName);
                    item.Tag = curr;
                    m_items.Add(curr.Id, item);
                }
            }
        }

        public void SetMainForm(IMainForm mainform)
        {
            m_mainForm = mainform;
        }

        public void UpdateButton()
        {
            m_mainForm.UpdateButton(toolBarMain.Buttons);
        }

        public void Init()
        {
            if (b_init) { return; } b_init = true;
            m_logic.Init();
            warehouseComboBox.DataSource = m_logic.WarehouseList;
            ccyComboBox.DataSource = m_logic.CurrencyList;
        }

        public void Refresh()
        {
            b_init = false;
            Init();
            m_logic.Refresh();
        }

        public void ClearForm()
        {
            tabPage1.Text = "";
            textBoxCode.Text = string.Empty;
            transactionDateDateTimePicker.Value = m_mainForm.GetGeneralSetup().StartEntryPeriod.StartDate;
            warehouseComboBox.SelectedItem = null;
            warehouseComboBox.Text = string.Empty;
            stoxkCheckBox.Checked = false;
            ccyComboBox.Text = string.Empty;
            ccyComboBox.SelectedItem = null;
            warehouseComboBox.Text = ServiceRegistry.GetInstance().GetDefaultDto(warehouseComboBox.DataSource as IList);
            ccyComboBox.Text = ServiceRegistry.GetInstance().GetDefaultDto(ccyComboBox.DataSource as IList);
            notesTextBox.Text = string.Empty;

            UserUpdateBy = string.Empty;
            LastUpdate = DateTime.Today;
            ComputerName = Environment.MachineName;
            dataGridView1.Rows.Clear();
            statusBar1.Text = string.Empty;
            //dataGridView1.RowCount = 500;
            //ClearEventGrid();
        }

        private void ClearEventGrid()
        {
            //dataGridView1.CellValidating -= new DataGridViewCellValidatingEventHandler(dataGridView1_CellValidating);
            //dataGridView1.CellValidated -= new DataGridViewCellEventHandler(dataGridView1_CellValidated);
            //for (int i = 0; i < 100; i++)
            //    dataGridView1.Rows.Add();
            //dataGridView1.CellValidating += new DataGridViewCellValidatingEventHandler(dataGridView1_CellValidating);
            //dataGridView1.CellValidated += new DataGridViewCellEventHandler(dataGridView1_CellValidated);
        }

        public void SetToReadOnly(bool readOnly)
        {
            textBoxCode.Enabled = !readOnly && !m_isAutoNumber;
            warehouseComboBox.Enabled = !readOnly;
            notesTextBox.Enabled = !readOnly;
            //postButton.Enabled = !readOnly;
            //stoxkCheckBox.Enabled = !readOnly;
            ccyComboBox.Enabled = !readOnly;
            dataGridViewTextBoxColumnCode.ReadOnly = readOnly;
            //dataGridViewTextBoxColumnName.ReadOnly = readOnly;
            //dataGridViewTextBoxColumnNo.ReadOnly = readOnly;
            dataGridViewTextBoxColumnPrice.ReadOnly = readOnly;
            dataGridViewTextBoxColumnQTY.ReadOnly = readOnly;
            //dataGridViewTextBoxColumnSubTotal.ReadOnly = readOnly;
            dataGridViewComboBoxColumnUOM.ReadOnly = readOnly;
            dataGridView1.AllowUserToAddRows = !readOnly;
            m_readOnly = readOnly;
        }

        public void SetButtonEditMode(Premiere.Window.EditMode editMode)
        {
            toolBarButtonNew.Enabled = buttonNew.Enabled = ((editMode.Equals(EditMode.OK) || editMode.Equals(EditMode.Empty))) && m_mainForm.GetRules(this.Name).New;
            toolBarButtonSave.Enabled = buttonSave.Enabled = ((editMode.Equals(EditMode.Edit) || editMode.Equals(EditMode.Insert))) && m_mainForm.GetRules(this.Name).New;
            toolBarButtonEdit.Enabled = buttonEdit.Enabled = ((editMode.Equals(EditMode.OK))) && m_mainForm.GetRules(this.Name).Edit;
            toolBarButtonDelete.Enabled = buttonDelete.Enabled = ((editMode.Equals(EditMode.OK) || editMode.Equals(EditMode.Edit))) && m_mainForm.GetRules(this.Name).Delete;
            toolBarButtonPrint.Enabled = m_mainForm.GetRules(this.Name).Print;
        }

        public void RemoveItem(long id)
        {
            if (m_items.ContainsKey(id))
            {
                ListViewItem item = (ListViewItem)m_items[id];
                listViewRecords.Items.Remove(item);
            }
        }

        public void FocusToCode()
        {
            textBoxCode.Focus();
        }

        public bool IsValidSubject()
        {
            errorProvider1.SetError(textBoxCode, "");
            //errorProvider1.SetError(textBoxName, "");
            bool a = (textBoxCode.Text == string.Empty) && !m_isAutoNumber;
            //bool b = textBoxName.Text == string.Empty;
            if (a) errorProvider1.SetError(textBoxCode, "Please fill Code");
            //if (b) errorProvider1.SetError(textBoxName, "Please fill Name");
            return !a;//&& !b;
        }

        public DateTime TransactionDate
        {
            get
            {
                return transactionDateDateTimePicker.Value;
            }
            set
            {
                transactionDateDateTimePicker.Value = value;
            }
        }

        public WarehouseDTO Warehouse
        {
            get
            {
                return warehouseComboBox.SelectedItem as WarehouseDTO;
            }
            set
            {
                warehouseComboBox.Text = value == null ? string.Empty : value.ToString();
            }
        }

        public string Notes
        {
            get
            {
                return notesTextBox.Text;
            }
            set
            {
                notesTextBox.Text = value;
            }
        }

        public EventStatus EventStatus
        {
            get
            {
                throw new Exception("The method or operation is not implemented.");
            }
            set
            {

                stoxkCheckBox.Checked = value.Equals(EventStatus.Confirm);
            }
        }

        public decimal TotalAllAmount
        {
            get
            {
                return (decimal)totalAmounttextBox.Tag;// totalAmounttextBox.Value;
            }
            set
            {
                totalAmounttextBox.Text = value.ToString(Tools.CreateFormat(TransactionCurrency.DecimalPlace));
                totalAmounttextBox.Tag = value;
            }
        }

        public CurrencyDTO TransactionCurrency
        {
            get
            {
                return ccyComboBox.SelectedItem as CurrencyDTO;
            }
            set
            {
                ccyComboBox.Text = value == null ? string.Empty : value.ToString();
            }
        }

        public void ClearError()
        {

        }



        public void SetIsAutoNumber(bool auto)
        {
            m_isAutoNumber = auto;
        }

        public IList GetValidItems()
        {
            IList items = new ArrayList();
            foreach (DataGridViewRow i in dataGridView1.Rows)
            {
                OpeningStockItemDTO item = itemDTO(i.Index);
                if (item == null) continue;
                if (item.Part == null) continue;
                // item.Amount = Convert.ToDecimal(dataGridView1[dataGridViewTextBoxColumnQTY.Index, i.Index].Value);
                // item.Price = Convert.ToDecimal(dataGridView1[dataGridViewTextBoxColumnPrice.Index, i.Index].Value);
                // item.Unit = (UnitDTO)Utils.FindDTOInListToString(dataGridView1[dataGridViewComboBoxColumnUOM.Index, i.Index].Value.ToString(), item.Part.GetAllUoM());
                // item.Warehouse = (WarehouseDTO)this.warehouseComboBox.SelectedItem;
                items.Add(item);
            }
            return items;
        }

        public void AddItem(OpeningStockItemDTO item)
        {
            int t = dataGridView1.Rows.Add("", item.Part.Code, item.Part.Name, item.Unit.Code,
                 item.Amount.ToString(), item.Price.ToString(Tools.CreateFormat(TransactionCurrency.DecimalPlace)),
                 item.TotalAmount.ToString(Tools.CreateFormat(TransactionCurrency.DecimalPlace)));
            ((DataGridViewComboBoxCell)dataGridView1[dataGridViewComboBoxColumnUOM.Index, t]).DataSource = Utils.GetListToString(item.Part.GetAllUoM());
            dataGridView1.Rows[t].Tag = item;

            //dataGridView1[dataGridViewTextBoxColumnPrice.Index, t].Style.Format = "N" + TransactionCurrency.DecimalPlace;
            //dataGridView1[dataGridViewTextBoxColumnSubTotal.Index, t].Style.Format = "N" + TransactionCurrency.DecimalPlace;

        }

        public void ClearRecordList()
        {
            listViewRecords.Items.Clear();
            m_items.Clear();
        }

        #endregion

        private void searchTextBox_Search(object sender, EventArgs e)
        {
            labelFound.Text = m_logic.Find(searchTextBox.Text);
        }
        private void searchTextBox_KeyUp(object objSender, KeyEventArgs objArgs)
        {

            if (objArgs.KeyData == Keys.Enter)
            {
                if (searchTextBox.Text == string.Empty)
                {
                    return;
                }
               labelFound.Text = m_logic.Find(searchTextBox.Text);
            }
        }

        private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            this.dataGridView1.Rows[e.RowIndex].HeaderCell.Value = (e.RowIndex + 1).ToString(); 
            SelectNextControl((Control)sender, true, true, true, true);
        }

        private void ccyComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            if (m_readOnly) return;
            for (int i = 0; i < dataGridView1.RowCount; i++)
            {
                dataGridView1[dataGridViewTextBoxColumnPrice.Index, i].Style.Format = "N" + TransactionCurrency.DecimalPlace;
                dataGridView1[dataGridViewTextBoxColumnSubTotal.Index, i].Style.Format = "N" + TransactionCurrency.DecimalPlace;
            }
        }
    }
}